package com.example.servlet.goods;

import com.example.bean.Goods;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-03 09:37
 **/
@WebServlet("/add_goods")
public class GoodsServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Goods goods = new Goods();
        try {
            BeanUtils.populate(goods, req.getParameterMap());
            HttpSession session = req.getSession();
            Map<String, Goods> map = (Map<String, Goods>) session.getAttribute("goods");
            if (map == null) {
                map = new HashMap<>();
                session.setAttribute("goods", map);
            }
            map.put(goods.getPid(), goods);
            req.getRequestDispatcher("/add_success.html").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
